import pandas as pd
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号 #有中文出现的情况，需要u'内容'

# 下载白酒数据
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data"
column_names = [
    "Class",
    "Alcohol",
    "Malic acid",
    "Ash",
    "Alcalinity of ash",
    "Magnesium",
    "Total phenols",
    "Flavanoids",
    "Nonflavanoid phenols",
    "Proanthocyanins",
    "Color intensity",
    "Hue",
    "OD280/OD315 of diluted wines",
    "Proline",
]

data = pd.read_csv(url, names=column_names)

# 选择类别标签为一类和二类的数据
selected_data = data[data["Class"].isin([1, 2])]

# 提取特征和类别标签
X = selected_data.drop("Class", axis=1)
y = selected_data["Class"]

# 使用PCA进行降维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# 使用LDA进行降维
lda = LinearDiscriminantAnalysis(n_components=min(X.shape[1], len(set(y)) - 1))
X_lda = lda.fit_transform(X, y)

# 打印 PCA 降维后的两维特征
print("PCA 降维后的两维特征:")
print(X_pca)

# 绘制 PCA 降维后的散点图
plt.figure(figsize=(8, 6))
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap="viridis", edgecolor="k", s=60)
plt.title("PCA降维后的散点图")
plt.xlabel("主成分1")
plt.ylabel("主成分2")
plt.show()

# 打印 LDA 降维后的两维特征
print("\nLDA 降维后的两维特征:")
print(X_lda)

# 绘制 LDA 降维后的散点图
plt.figure(figsize=(8, 6))
plt.scatter(X_lda[:, 0], X_lda[:, 0], c=y, cmap="viridis", edgecolor="k", s=60)
plt.title("LDA降维后的散点图")
plt.xlabel("线性判别1")
plt.ylabel("线性判别2")
plt.show()